package cn.t235.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/10/28.
 */
@Aspect
@Component
public class UserServiceLogger {
    private Logger logger = Logger.getLogger(getClass());
    @Pointcut("execution(* cn.t235.service..*.*(..))")
    public void p1() {}

    @Before("p1()")
    public void before(JoinPoint jp) {
        logger.info("前置增强：");
        logger.info("方法名：" + jp.getSignature().getName());
        logger.info("参数：" + Arrays.toString(jp.getArgs()));
    }
    @AfterReturning(pointcut = "p1()", returning = "returnValue")
    public void afterReturning(JoinPoint jp, Object returnValue) {
        logger.info("后置增强：");
        logger.info("方法名：" + jp.getSignature().getName());
        logger.info("参数：" + Arrays.toString(jp.getArgs()));
        logger.info("返回值：" + returnValue);
    }
    @AfterThrowing(pointcut = "p1()", throwing = "ex")
    public void afterThrowing(JoinPoint jp, NullPointerException ex) {
        logger.info("异常增强：");
        logger.info("方法名：" + jp.getSignature().getName());
        logger.info("参数：" + Arrays.toString(jp.getArgs()));
        logger.info("异常：" + ex.getMessage());
    }

    @After("p1()")
    public void after(JoinPoint jp) {
        logger.info("最终增强：");
        logger.info("方法名：" + jp.getSignature().getName());
        logger.info("参数：" + Arrays.toString(jp.getArgs()));
    }

    @Around("p1()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        logger.info("环绕增强：");
        logger.info("方法名：" + jp.getSignature().getName());
        logger.info("参数：" + Arrays.toString(jp.getArgs()));
        Object ret = null;
        // 调用目标方法
        ret =jp.proceed();
        logger.info("环绕增强：[结束,返回值是]" + ret);
        return ret;
    }
}
